#pragma once

#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Err.hpp"

static int gbacklog = 20;
static const int defaultval = -1;

class Sock
{
public:
    Sock() : _listensock(defaultval)
    {
    }
    ~Sock()
    {
        if(_listensock != defaultval) close(_listensock);
    }

public:
    void Socket()
    {
        // 1.创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logMessage(FATAL, "creat socket error");
            exit(SOCK_ERR);
        }
        logMessage(NOMAL, "creat socket success: %d", _listensock);
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        // 利用 SO_REUSEADDR 选项，允许套接字绑定到已被使用的地址，常用于服务器程序快速重启，避免因地址处于 TIME_WAIT 状态无法绑定。
    }

    void Bind(int port)
    {
        // 2.bind自己的网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind socket error");
            exit(BIND_ERR);
        }
        logMessage(NOMAL, "bind socket success");
    }

    void Listen()
    {
        // 3.设置sock为listen监听状态
        if (listen(_listensock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen socket error");
            exit(LISTEN_ERR);
        }
        logMessage(NOMAL, "listen socket success");
    }

    int Accept(std::string *clientip, uint16_t *clientport,int* err)
    {
        struct sockaddr_in peer;
        socklen_t peerlen = sizeof(peer);
        int sock = accept(_listensock, (struct sockaddr *)&peer, &peerlen);
        *err = errno;
        if (sock < 0)
        {
            logMessage(ERROR, "accept error,next");
        }
        else
        {
            logMessage(NOMAL, "accept new link success");
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }
        return sock;
    }
    int Fd()
    {
        return _listensock;
    }
    void Close()
    {
        if(_listensock != defaultval) close(_listensock);
    }
private:
    int _listensock;
};